package com.webchat.user.service.relation;

import com.webchat.common.enums.AccountRelationTypeEnum;
import com.webchat.common.enums.messagequeue.MessageBroadChannelEnum;
import com.webchat.common.exception.BusinessException;
import com.webchat.common.service.FreeMarkEngineService;
import com.webchat.common.service.MinioService;
import com.webchat.common.service.messagequeue.producer.MessageQueueProducer;
import com.webchat.common.util.FreemarkerUtils;
import com.webchat.common.util.ThreadPoolExecutorUtil;
import com.webchat.domain.vo.request.CreateGroupRequestVO;
import com.webchat.domain.vo.response.UploadResultVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service
public class User2GroupAccountRelationService extends AbstractAccountRelationService {


    @Autowired
    private MinioService minioService;

    private static final String GROUP_PHOTO_TEMPLATE = "group_photo.ftl";

    @Override
    protected AccountRelationTypeEnum getRelationType() {

        return AccountRelationTypeEnum.USER_GROUP;
    }

    @Override
    protected boolean isAsyncDoAfterComplete() {

        return false;
    }

    @Override
    protected void doAfterComplete(Long id, String sourceAccount, String targetAccount, boolean subscribe) {
        // 添加群聊到用户账号关系列表
        if (subscribe) {
            super.init(targetAccount, sourceAccount);
            super.addTargetAccountRelationListCache(targetAccount, sourceAccount);
            super.init(sourceAccount, targetAccount);
            super.addTargetAccountRelationListCache(sourceAccount, targetAccount);
            // 添加群聊到用户聊天对话列表缓存
            super.addTargetAccount2SourceLastChattingList(sourceAccount, targetAccount);
        }
    }


    /**
     * 创建群聊
     *
     * @param requestVO
     * @return
     */
    @Transactional
    public String createChatGroup(CreateGroupRequestVO requestVO) {
        Set<String> groupUserIds = requestVO.getUserIds();
        // 添加当前创建人作为群成员
        groupUserIds.add(requestVO.getCreateUserId());
        List<String> groupUserIdList = new ArrayList<>(groupUserIds);
        // 走redis批量查询群成员详情
        List<UserBaseResponseInfoVO> groupUsers = super.userService.batchGetUserListInfoFromCache(groupUserIdList);
        // 1. 生成群昵称
        // 群昵称：默认去前三个用户的昵称拼接
        String groupName = this.genGroupName(groupUsers);
        // 2. 生成群头像
        // 取前9个用户头像合成一张新图片作为群头像
        String groupPhoto = this.genGroupPhoto(groupUsers);
        System.out.println("创建群聊生成头像: " + groupPhoto);
        // 3. 入库 mysql
        String groupId = userService.registerGroup2DB(groupName, groupPhoto, requestVO.getCreateUserId());
        // 4. 刷新redis缓存
        // 5. MQ添加最新群聊到群成员对话列表头部
        ThreadPoolExecutorUtil.execute(() ->
            groupUserIds.forEach(uid -> {
                // 4.1 刷新账号详情缓存(在registerGroup2DB中已经实现)
                // 4.2 刷新群下成员列表缓存 == 每个用户订阅群组，服用现有的账号关系服务
                super.subscribe(uid, groupId);
                // 5.1 MQ添加最新群聊到群成员对话列表头部
                // 5.2 MQ + WS通知刷新用户会话列表（super.addTargetAccount2SourceLastChattingList加入并刷新）
                // 刷新所有群组用户最新对话列表（最新创建群聊）
                super.addTargetAccount2SourceLastChattingList(uid, groupId);
            }));
        return groupId;
    }

    /**
     * 群昵称：默认取前三个用户的昵称拼接
     * @param groupUsers
     * @return
     */
    private String genGroupName(List<UserBaseResponseInfoVO> groupUsers) {
        List<UserBaseResponseInfoVO> top3Users = groupUsers.subList(0, 3);
        StringBuilder sb = new StringBuilder();
        for (UserBaseResponseInfoVO u : top3Users) {
            sb.append(u.getUserName()).append("、");
        }
        return sb.toString().substring(0, sb.length() - 1);
    }

    /**
     * 合成群头像
     *
     * @param groupUsers
     * @return
     */
    private String genGroupPhoto(List<UserBaseResponseInfoVO> groupUsers) {

        // 1. 取前9个用户头像合成新图片
        List<UserBaseResponseInfoVO> top9Users = groupUsers.subList(0, Math.min(9, groupUsers.size()));
        List<String> photos = top9Users.stream().map(UserBaseResponseInfoVO::getPhoto).collect(Collectors.toList());
        // 合成图片
        Map<String, Object> vars = new HashMap<>();
        vars.put("photos", photos);
        BufferedImage bufferedImage;
        try {
            bufferedImage = FreemarkerUtils.turnImage(GROUP_PHOTO_TEMPLATE, vars, 300);
        } catch (Exception e) {
            log.error("创建群聊异常 =====> 头像生成失败.", e);
            throw new BusinessException("头像生成失败");
        }
        // 2. 头像上传OS
        UploadResultVO uploadResult = minioService.upload(bufferedImage);
        return uploadResult.getUrl();
    }
}
